/**
 * @文件名称: TermQuartz.java
 * @版权声明 : Copyright (C) 2008-2016 北斗天汇（北京）科技有限公司
 * @创建人员: 徐斌
 * @文件描述:
 * @修改时间: 2017年6月16日 上午8:58:04
 * @修改历史： 2017年6月16日
 */

package com.bdth.controller;

import com.bdth.model.*;
import com.bdth.service.IDepartmentService;
import com.bdth.service.IDeviceService;
import com.bdth.service.IUserService;
import com.bdth.utils.HtmlUtil;
import com.bdth.utils.SessionUtils;
import com.bdth.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/dep")
public class DepartmentController extends BaseController {

	@Autowired
	private IDepartmentService departmentService;

	@Autowired
	private IDeviceService deviceService;

	@Autowired
	private IUserService userService;

	/**
	 * 首页
	 *
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request)
			throws Exception {
		return forword("/department/depList");
	}

	/**
	 * json 列表页面
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/dataList")
	public void dataList(PageModel pageModel, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		User user = SessionUtils.getUser(request);
		String depName = request.getParameter("depName");
		map.put("depName", depName);
		List<Integer> depIds = getDepIds(user.getDepId());
		map.put("depIds", depIds);

		//紧跟着的第一个查询方法会被分页
		PageHelper.startPage(pageModel.getPage(), pageModel.getRows());
		List<Map> dataList = departmentService.queryMapDataByMapList(map);
		//获得结果集条总数
		PageInfo pageList = new PageInfo(dataList);
		//设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", pageList.getTotal());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}


	@RequestMapping("/getId")
	public void getId(Integer id, HttpServletResponse response)
			throws Exception {
		Map<String, Object> context = getRootMap();
		Department bean = departmentService.queryById(id);
		if (bean == null) {
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}


	/**
	 * 添加或修改数据
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public void save(Department bean, HttpServletResponse response)
			throws Exception {
		Map<String, Object> context = new HashMap<String, Object>();
		if (bean.getParentDepId().intValue() == 0 || StringUtil.isEmptyWithNullStr(bean.getParentDepName())) {
			sendFailureMessage(response, "请选择上级分组!");
			return;
		}
		if (bean.getId() == null) {
			departmentService.add(bean);
		} else {
			if (bean.getId().intValue() > 0 && bean.getId().intValue() == bean.getParentDepId().intValue()) {
				sendFailureMessage(response, "上级分组不能是本分组!");
				return;
			}

			List<Integer> depIds = getDepIds(bean.getId());
			if (depIds.contains(bean.getParentDepId().intValue())) {
				sendFailureMessage(response, "上级分组不能同时是本分组的下级分组!");
				return;
			}

			departmentService.updateBySelective(bean);
		}
		sendSuccessMessage(response, "保存成功~");
	}


	@RequestMapping("/delete")
	public void delete(Integer[] id, HttpServletResponse response)
			throws Exception {
		departmentService.delete(id);
		sendSuccessMessage(response, "删除成功");
	}

	/**
	 * 假删除
	 *
	 * @param id
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/fakeDelete")
	public void fakeDelete(Integer[] id, HttpServletResponse response)
			throws Exception {

		for (int i : id) {
			List<Integer> depIds = new ArrayList<>();
			depIds.add(i);
			List<Device> deviceList = deviceService.queryByDepIds(depIds);
			if (deviceList != null && deviceList.size() > 0) {
				sendFailureMessage(response, "该分组下分配有设备，不能删除!");
				break;
			}

			List<Department> depList = departmentService.selectByPId(i);
			if (depList != null && depList.size() != 0) {
				sendFailureMessage(response, "分组下分配有子分组，不能删除!");
				break;
			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("depIds", depIds);
			List<User> userList = userService.queryByMapList(map);
			if (userList != null && userList.size() > 0) {
				sendFailureMessage(response, "该分组下分配有用户，不能删除!");
				break;
			}


			Department department = new Department();
			department.setId(i);
			department.setDeleted(1);
			departmentService.deleteFake(department);
			sendSuccessMessage(response, "删除成功");
		}

	}

	@RequestMapping("/parentDepTree")
	public void parentDepTree(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String path = request.getContextPath();
		Map<String, Object> map = new HashMap<String, Object>();
		List<ZTreeNode> nodeList = new ArrayList<ZTreeNode>();
		User user = SessionUtils.getUser(request);
		List<Integer> depIds = getDepIds(user.getDepId());
		map.put("depIds", depIds);
		List<Department> list = departmentService.queryByMapList(map);
		for (Department bd : list) {
			String parentId = bd.getParentDepId().intValue() == 0 ? null : ("" + bd.getParentDepId());
			if (StringUtil.isEmptyWithNullStr(parentId)) {
				parentId = "0";
			}
			ZTreeNode node = new ZTreeNode("" + bd.getId(), bd.getDepName(), parentId, path + "/static/plugins/ztree/css/zTreeStyle/img/diy/dep.png", false);
			nodeList.add(node);
		}
		//ZTreeNode rootNode = new ZTreeNode("0", "请选择分组", "0", path + "/static/plugins/ztree/css/zTreeStyle/img/diy/dep.png", true);
		//nodeList.add(rootNode);

		HtmlUtil.writerJson(response, nodeList);
	}


	@RequestMapping("/depTree")
	public void depTree(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String path = request.getContextPath();
		Map<String, Object> map = new HashMap<String, Object>();
		User user = SessionUtils.getUser(request);
		List<Integer> depIds = getDepIds(user.getDepId());
		map.put("depIds", depIds);
		List<Department> list = departmentService.queryByMapList(map);
		List<ZTreeNode> nodeList = new ArrayList<ZTreeNode>();
		for (Department bd : list) {
			String parentId = bd.getParentDepId().intValue() == 0 ? null : ("" + bd.getParentDepId());
			if (StringUtil.isEmptyWithNullStr(parentId)) {
				parentId = "0";
			}
			ZTreeNode node = new ZTreeNode("" + bd.getId(), bd.getDepName(), parentId, path + "/static/plugins/ztree/css/zTreeStyle/img/diy/dep.png", false);
			nodeList.add(node);
		}

		HtmlUtil.writerJson(response, nodeList);
	}

}
